﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Xml;
using System.Reflection;

namespace ServiceLibrary.BLayer
{
    public class AcknowledgementError
    {
        public AcknowledgementError() { }

        public static T CreateMessage<T>(Type _type, string errorDetail, string traceDetail)
        {
            object retInstance = new object();

            try
            {
                #region Estrazione messaggio da DB

                string xmlResponse = Function.ErrorManager(ENUM.ACK_CODE_FAIL, errorDetail, _type.FullName);

                #endregion

                #region Deserializzo buffer

                object obj = Function.DeserializeFromXmlString(xmlResponse, _type);
                retInstance = Convert.ChangeType(obj, _type);

                #endregion

                #region Generazione Messaggio SOAP

                string envelope = ServiceLibrary.BLayer.X509SecurityService.EnevelopeDefinition(xmlResponse, _type.FullName);

                XmlDocument xmlSoapRequest = new XmlDocument();
                xmlSoapRequest.LoadXml(envelope);

                #endregion

                #region GUID ACK

                string _guidAck = Guid.NewGuid().ToString();

                #endregion

                #region Trace : ACK

                Function.SISM_Soap_Log(_guidAck, envelope, _type.ToString() + ": " + traceDetail);

                #endregion
            }
            catch{

                /*
                    In caso estremo l'ACK non verrà tracciato sulla tabella di Trace
                 */

                var generic = (T)Activator.CreateInstance(_type);

                ServiceLibrary.Model.ERROREType erroreGenerico = new ServiceLibrary.Model.ERROREType();

                erroreGenerico.CODICE = ENUM.ACK_CODE_FAIL;
                erroreGenerico.MESSAGGIO = ENUM.ACK_MSG_FAIL;

                generic.GetType().GetProperty("ERRORE").SetValue(generic, erroreGenerico, null);

                retInstance = Convert.ChangeType(generic, _type);
            }

            return (T)retInstance;
        }

    }
}
